package com.dgut.lotterySystem.service.impl;

import com.dgut.lotterySystem.common.errorcode.ServiceErrorCodeConstants;
import com.dgut.lotterySystem.common.pojo.exception.ServiceException;
import com.dgut.lotterySystem.controller.param.CreatePrizeParam;
import com.dgut.lotterySystem.controller.param.PageParam;
import com.dgut.lotterySystem.dao.dataObject.PrizeDO;
import com.dgut.lotterySystem.dao.dataObject.PrizeInfoDO;
import com.dgut.lotterySystem.dao.mapper.PrizeMapper;
import com.dgut.lotterySystem.service.IPrizeService;
import com.dgut.lotterySystem.service.dto.PageInfoListDTO;
import com.dgut.lotterySystem.service.dto.PrizeInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
public class PrizeServiceImpl implements IPrizeService {
    @Autowired
    private PictureServiceImpl pictureService;

    @Autowired
    private PrizeMapper prizeMapper;
    @Override
    public Long createPrize(CreatePrizeParam param, MultipartFile prizePic) {
        //保存图片
        String image_url=pictureService.savePicture(prizePic);
        //保存数据

        PrizeDO prizeDO=new PrizeDO();
        prizeDO.setName(param.getPrizeName());
        prizeDO.setDescription(param.getDescription());
        prizeDO.setPrice(param.getPrice());
        prizeDO.setImageUrl(image_url);

        int ret=prizeMapper.insert(prizeDO);
        if(ret!=1){
            throw new ServiceException(ServiceErrorCodeConstants.PRIZE_SAVE_ERROR);
        }

        return prizeDO.getId();
    }

    @Override
    public PageInfoListDTO<PrizeInfoDTO> getPageInfoList(PageParam param){
        //总量
        Integer total=prizeMapper.count();
        //查全部
        List<PrizeInfoDTO> prizeInfoDTOList =new ArrayList<>();
        List<PrizeInfoDO> prizeInfoDOList=prizeMapper.selectPrizeInfoList(param.offset(),param.getPageSize());
        for(PrizeInfoDO prizeInfo:prizeInfoDOList){
            PrizeInfoDTO prizeInfoDTO=new PrizeInfoDTO();
            prizeInfoDTO.setId(prizeInfo.getId());
            prizeInfoDTO.setName(prizeInfo.getName());
            prizeInfoDTO.setDescription(prizeInfo.getDescription());
            prizeInfoDTO.setPrice(prizeInfo.getPrice());
            prizeInfoDTO.setImageUrl(prizeInfo.getImageUrl());
            prizeInfoDTOList.add(prizeInfoDTO);
        }
        return new PageInfoListDTO<>(total,prizeInfoDTOList);
    }
}
